package org.example.testdemo.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import org.example.testdemo.pojo.PageReq;
import org.example.testdemo.pojo.Project;
import org.example.testdemo.pojo.User;
import org.example.testdemo.pojo.combination.ProjectList;
import org.example.testdemo.pojo.combination.ProjectPid;
import org.example.testdemo.pojo.combination.ProjectUpdate;
import org.example.testdemo.service.DepartmentService;
import org.example.testdemo.service.ProjectService;
import org.example.testdemo.service.UserService;
import org.example.testdemo.tool.ApiResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("project")
@Validated
@CrossOrigin
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private UserService userService;

    @PostMapping("addProject")
    @Transactional
    public ApiResponse addProject(@Validated Project project) {
        //判断该项目编号数据库是否存在
        Project projects = projectService.querySubordinateProjects(project.getPId());
        if(projects!=null){
            return ApiResponse.fail(20000,"该项目已存在");
        }
        //父级项目编号
        String superiorProject = "";
        //判断编号合法性
        if(project.getPId().length()>3){
            String substring = project.getPId().substring(3);
            if(substring.length()%2>0){
                return ApiResponse.fail(20000,"编号不符合规范");
            }
            //获取一级编号
            StringBuilder substringed = new StringBuilder(project.getPId().substring(0, 3));
            if(substring.length()-2<=0){
                Project queried = projectService.querySubordinateProjects(substringed.toString());
                if(queried==null){
                    return ApiResponse.fail(20000,"编号"+substringed+"没有创建");
                }
                superiorProject = substringed.toString();
            }else if(substring.length()/2>2){
                return ApiResponse.fail(20000,"编号不符合规范");
            }else {
                substringed.append(substring.charAt(0)).append(substring.charAt(1));
                superiorProject = substringed.toString();
                Project queried = projectService.querySubordinateProjects(substringed.toString());
                if(queried==null){
                    return ApiResponse.fail(20000,"编号"+substringed.toString()+"没有创建");
                }
            }
            //添加级次
            project.setLevel((substring.length() / 2)+1);
        }else{
            project.setLevel(1);
        }
        //判断部门是否合法
        String bCode = departmentService.findByBCode(project.getBCode());
        if(bCode==null){
            return ApiResponse.fail(20000,"不是有效的部门");
        }
        //判断用户的合法性
        User userIdAndBCode = userService.findByUserIdAndBCode(project.getUserId(), bCode.split("/")[0]);
        if(userIdAndBCode==null){
            return ApiResponse.fail(20000,"不是有效的项目负责人");
        }
        System.out.println(superiorProject);
        //修改上级项目明细
        if(!superiorProject.isEmpty()){
            projectService.updateDetails(superiorProject);
        }
        project.setBalance(project.getInitialAmount());
        //新增项目信息
        Integer inserted = projectService.insertProject(project);
        if(inserted<=0){
//            throw new Exception("项目信息新增失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ApiResponse.success();
    }

    @PostMapping("getProject")
    public ApiResponse getProject(@NotNull(message = "缺少必要参数") String pName){
        return ApiResponse.success(projectService.getProjectPname(pName));
    }

    @PostMapping("queryProject")
    public ApiResponse queryProject(@NotNull(message = "缺少必要参数") String pId){
        if(pId.length()<3 || pId.length()>7){
            return ApiResponse.fail(20002,"项目编号不符合规范");
        }else {
            //查询项目是否存在
            Project project = projectService.querySubordinateProjects(pId);
            if(project == null){
                if(pId.length() == 3){
                    return ApiResponse.fail(20002,"项目编号"+pId+"不存在");
                }
                //获取一级编号
                StringBuilder substringed = new StringBuilder(pId.substring(0, 3));
                String substring = pId.substring(3);
                if(substring.length()%2>0){
                    return ApiResponse.success("编号不符合规范");
                }else{
                    if(substring.length()/2==2){
                        return ApiResponse.success("项目编号"+ substringed.append(substring.charAt(0)).append(substring.charAt(1)).toString()+"不存在");
                    }else{
                        return ApiResponse.success("项目编号"+substringed.toString()+"不存在");
                    }
                }
            }else if(project.getPId().length()==7){
                return ApiResponse.success("该项目已存在且已到达最大层级");
            }

            //查询下级项目
            List<ProjectPid> pidList = projectService.subordinateProjects(pId);
            //编号
            String newPId = "";
            if(pidList.size()-1==0){
                newPId = "01";
            }else{
                List<Integer> pidListInt=null;
                if(pId.length()>3){
                    pidListInt = new ArrayList<>();
                    for (ProjectPid projectPid : pidList){
                        if(projectPid.getValue().length()<=pId.length()){
                            continue;
                        }
                        String substring = projectPid.getValue().substring(pId.length(), (pId.length() + 2));
                        pidListInt.add(Integer.parseInt(substring));
                    }
                }else{
                    pidListInt = new ArrayList<>();
                    for (ProjectPid projectPid : pidList) {
                        String substring = projectPid.getValue().substring(3);
                        if(substring.length()<=2 && !substring.isEmpty()){
                            pidListInt.add(Integer.parseInt(substring));
                        }
                    }
                }
                Collections.sort(pidListInt);
                if(pidListInt.getFirst()!=1){
                    newPId = "01";
                }
                for (int i = 0; i < pidListInt.size(); i++) {
                    if((i+1)<pidListInt.size()){
                        if(pidListInt.get(i)+1 != pidListInt.get(i+1)){
                            newPId = String.valueOf(pidListInt.get(i)+1).length()<2 ? String.valueOf("0"+(pidListInt.get(i)+1)) : String.valueOf(pidListInt.get(i)+1);
                        }
                    }else{
                        newPId = String.valueOf(pidListInt.get(i)+1).length()<2 ? String.valueOf("0"+(pidListInt.get(i)+1)) : String.valueOf(pidListInt.get(i)+1);
                    }
                }
            }
            //创建返回数据
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("pid",pId+newPId);
            hashMap.put("balanceDirection",project.getBalanceDirection());
            hashMap.put("bCode",departmentService.findByBCode(project.getBCode()));
            return ApiResponse.success(hashMap);
        }
    }

    @PostMapping("getProjects")
    public ApiResponse getProjects(String pName, String bCode, String name,String pId, PageReq pageReq){
        if(null == pName || pName.isEmpty()){
            pName = null;
        }
        if (null == bCode || bCode.isEmpty()) {
            bCode = null;
        }
        if (null == name || name.isEmpty()) {
            name = null;
        }
        if (null == pId || pId.isEmpty()) {
            pId = null;
        }
        pageReq.setSize(10);
        return ApiResponse.success(projectService.getProjectList(pName,bCode,name,pId,pageReq));
    }

    @PostMapping("obtainProjectInformation")
    public ApiResponse obtainProjectInformation(@NotNull(message = "缺少必需参数") String projectId){
        ProjectUpdate projectUpdate = projectService.obtainProjectInformation(projectId);
        projectUpdate.setStateEnable(projectUpdate.getState()==1);
        return ApiResponse.success(projectUpdate);
    }

    @PostMapping("updateProject")
    @Transactional
    public ApiResponse updateProject(@Validated ProjectUpdate projectUpdate, HttpServletRequest request){
        //获取项目信息
        Project project = projectService.querySubordinateProjects(projectUpdate.getPId());
        if(project==null){
            return ApiResponse.fail(20000,"项目不存在");
        }
        //获取用户信息
        User idAndBCode = userService.findByUserIdAndBCode(projectUpdate.getUserId(), project.getBCode());
        if(idAndBCode==null){
            return ApiResponse.fail(20000,"该用户无法管理此项目");
        }
        //获取session
        HttpSession session = request.getSession();
        //获取用户id与权限
        Integer permissionId = (Integer) session.getAttribute("permissionId");
        //判断是否具有修改权限
        if(permissionId == 1){
            //判断上级项目状态
            String substring = project.getPId().substring(3);
            if(substring.length()>1){
                StringBuilder substringed = new StringBuilder(project.getPId().substring(0, 3));
                if(substring.length()/2==2){
                    substringed.append(substring.charAt(0)).append(substring.charAt(1));
                }
                //获取上级项目状态
                Project queried = projectService.querySubordinateProjects(substringed.toString());
                if(queried == null){
                    ApiResponse.error();
                }else if(queried.getState() == 0 && projectUpdate.getState() == 1){
                    return ApiResponse.fail(20000,"上级项目没有启用,当前项目不允许启用");
                }else if(queried.getState() == 1){
                    //修改全部下级项目
                    projectService.updateProjectAll(project.getPId(),projectUpdate.getState());
                }
            }else{
                //修改全部下级项目
                projectService.updateProjectAll(project.getPId(),projectUpdate.getState());
            }

            //修改项目信息
            project.setUserId(projectUpdate.getUserId());
            project.setPName(projectUpdate.getPName());
            project.setBalanceDirection(projectUpdate.getBalanceDirection());
            project.setLimitPayment(BigDecimal.valueOf(projectUpdate.getLimitPayment()));
            project.setState(projectUpdate.getState());

            Integer updateProject = projectService.updateProject(project);
            if(updateProject<=0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ApiResponse.fail(20000,"修改项目失败");
            }
            return ApiResponse.success();
        }
        return ApiResponse.fail(20000,"无权限修改此项目");
    }


    @PostMapping("deleteProject")
    public ApiResponse deleteProject(@NotNull(message = "请选择要删除的项目") String[] pId){
        if(pId.length<1){
            return ApiResponse.fail(20000,"请选择要删除的项目");
        }
        List<String> pIdList = new ArrayList<>();
        for (String string : pId) {
            List<ProjectPid> pidList = projectService.subordinateProjects(string);
            pidList.forEach((value) -> {
                pIdList.add(value.getValue());
            });
        }
        Integer project = projectService.deleteProject(pIdList);
        if(project<=0){
            return ApiResponse.fail(20000,"项目删除失败");
        }
        return ApiResponse.success();
    }

    @PostMapping("deleteProjectSingle")
    public ApiResponse deleteProjectSingle(@NotNull(message = "参数异常") String pId){
        //查询是否有下级项目
        List<ProjectPid> pidList = projectService.subordinateProjects(pId);
        if(pidList.size()>1){
            return ApiResponse.fail(20000,"项目下有子项目，必须先删除子项目");
        }
        Integer integer = projectService.deleteProjectSingle(pId);
        if(integer<=0){
            return ApiResponse.fail(20000,"项目删除失败");
        }
        return ApiResponse.success();
    }

    @PostMapping("getMyProjects")
    public ApiResponse getMyProjects(String name,String pId, PageReq pageReq,HttpServletRequest request){
        if (null == name || name.isEmpty()) {
            name = null;
        }
        if (null == pId || pId.isEmpty()) {
            pId = null;
        }
        pageReq.setSize(10);
        return ApiResponse.success(projectService.getMyProjects(name,pId,(String) request.getSession().getAttribute("userId"),pageReq));
    }

    @PostMapping("getAutProjectList")
    public ApiResponse getAutProjectList(HttpServletRequest request){
        return ApiResponse.success(projectService.getAutProjectList((String) request.getSession().getAttribute("userId")));
    }

    @PostMapping("authorizeProject")
    public ApiResponse authorizeProject(HttpServletRequest request,String pName,String pId, PageReq pageReq){
        if (null == pName || pName.isEmpty()) {
            pName = null;
        }
        if (null == pId || pId.isEmpty()) {
            pId = null;
        }
        pageReq.setSize(10);
        return ApiResponse.success(projectService.authorizeProject((String) request.getSession().getAttribute("userId"),pName,pId,pageReq));
    }

}
